
/*
*Released on 28th June 2008.
*Any violations can be reported at paritosh@wikiocean.net
*What is treated as violations can be found at www.wikiocean.net/ppl1-voilations*
******************************************************************************
* The contents of this file are subject to POOL Public License 1.0 and later.
* POOL Public License is based on Affero GPL v3 and additional conditions.
* ("License"); You may not use this file except in compliance with the License
* You may obtain a copy of the Affero GPL v3 License at http://www.gnu.org/licenses/agpl.html
* You may obtain a copy of the POOL Public License 1.0 or later at www.wikiocean.net/license/ppl.html
* Software distributed under POOL Public License 1.0 is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
* the specific language governing rights and limitations under the License.
* The Initial Developer of the Original Code is Paritosh Pungaliya (C) 2008. All Rights Reserved.
******************************************************************************
* Objective of the additional terms (license)
* 1) Is to extend the software freedom to freedom to work.
* 2) To ensure that knowledge is free from monopoly of agencies.
* 3) To avoid a situation where big corporate or investor can buy out free software groups and companies and then start milking the communities built around it.
* (this trend can be seen how the freedom is curtailed in companies that get Venture Capital funding.)
******************************************************************************
*/

package  smsBean;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;

import logger.PoolLogger;
import control.Command;
import dbmanager.DBManager;
import dbmanager.GetIdName;
import utility.ConvertToLower;
import utility.Index;


public class SmsTd_property_details extends SubSmsBean
{

	private String tdpl_tableName = "td_property_details";
	private String td_tableName = "transaction_details";

	private Hashtable<Object,Object> TransdetailsHash = new Hashtable<Object, Object>();	 
	private Vector<Object> TdPropertyList = new Vector<Object>();
	 
	private Vector<Object> OldTdPropertyList = new Vector<Object>();
	private Vector<Object> NewTdPropertyList = new Vector<Object>();
	  
	private String msg;
	private String TdPropertySPchar = "";	
	
	private String tdid="";
	 
	private Hashtable<Object,Object> ViewHashtable = new Hashtable<Object, Object>();
	PoolLogger pl;
	
	// Td_property_details_Bean tdplBean; 
	 
	public SmsTd_property_details(){
		// logger
		pl = (PoolLogger) PoolLogger.getLogger(this.getClass().getName());
	}
	public SmsTd_property_details( String msg, String process,String Request) 
	{
		this.request = Request;
		this.process = process;
		message = msg;
		this.msg = msg;
		
		// logger
		pl = (PoolLogger) PoolLogger.getLogger(this.getClass().getName());
	}
	
	
	/**
	 * In initialize method of Td_property_details put the hashMap in
	 * PropertyMap hashtable
	 * 
	 * @return PropertyMap is a Hashtable which stores object of
	 *         Td_property_details class which is presents in hashtable.
	 *         hashtable contains the all the fields of Td_property_details
	 *         which presents in given message e.g. Tdid,pid,pv,vt,ref.
	 * 
	 */
	@SuppressWarnings("unchecked")
	public Hashtable<Object, Object> initializeToAdd() 
	{
		Hashtable<Object, Object> PropertyMap = new Hashtable<Object, Object>();
		
		PropertyMap.putAll(initTransactiondetailsPropertyDetails());
		
		if(PropertyMap.containsKey("ErrorInput"))
		{
			
			System.out.println("Error");
			return PropertyMap;
		}
		
		insertTdid(tdid);
		return PropertyMap;
	}

	
	/**
	 * this function inserts tdid in each hashtable given in PropertyVector
	 *  @param tdid - stores tdid as a string value
	 */
	@SuppressWarnings("unchecked")
	private void insertTdid(String tdid)
	{
		for(Object object : TdPropertyList)
		{
			Hashtable<Object,Object> tempHash = (Hashtable<Object, Object>)object;
			tempHash.put("tdid",tdid);			
		}
		
	}

	/**
	 * In this method it splits all properties and creats an object of each
	 * property which stores in hashmap.Then add these hashmap in TdPropertyList
	 * vector.
	 * 
	 * @return PropertyMap If propertryMap of TDPL contains an error Input then
	 *         it returns an error message otherwise it return a propertyMap
	 *         which cointains object of TDPL.
	 * 
	 */

	public Hashtable<Object, Object> initTransactiondetailsPropertyDetails()
	{
		int index = 0;
		int pCount;
		 String masterTable = "transaction";
		Hashtable<Object, Object> PropertyMap = new Hashtable<Object, Object>();
		
		Command cp = new Command(masterTable);
		pCount = cp.getCountof(message, tdpl_tableName, process);
		
		if (pCount != 0) 
		{
			TdPropertySPchar = cp.getSPchar();
			index = Index.indexOf(message, TdPropertySPchar, index + 1);
		}
		
		if(TdPropertySPchar.length()>0)
		{
			msg= message.substring(0,Index.indexOf(message, TdPropertySPchar));
			
			Hashtable<Object,Object> TransdetailsMap = new Hashtable<Object, Object>();
			 
			TransdetailsMap.putAll(cp.getHashCommand(td_tableName,msg,process));
			if(TransdetailsMap.containsKey("ErrorInput"))
			{
				PropertyMap.put("ErrorInput", TransdetailsMap.get("ErrorInput"));
				return PropertyMap;
			}
			
			Enumeration< Object> enum1 = TransdetailsMap.keys();
			if(enum1.hasMoreElements()==false)
			{
				TransdetailsMap.put("ErrorInput","check tid,item,qty or property presents properly");
					return TransdetailsMap;
			}
			String id="";
			try 
			{
				GetIdName gin = new GetIdName();
				TransdetailsMap = gin.getHashMapOfValues(TransdetailsMap);
				TransdetailsHash.putAll(TransdetailsMap);
				TransdetailsMap=gin.convertMasterId(TransdetailsMap, td_tableName, process);
				ResultSet rs = DBManager.getselect(TransdetailsMap,td_tableName);				
				rs.next();
				id = rs.getString("id");
				tdid = id;
			} 
			catch (Exception e){}
			
		}
		
		String msg = "";
		while (pCount != 0) 
		{
			if (index == -1) 
			{
				break;
			}
			pCount--;
			try {
				int start = 0;
				int end = 0;

				start = index;
				msg = message.substring(start + 1);
				if (msg.contains(TdPropertySPchar))
				{
					end = Index.indexOf(msg, TdPropertySPchar) + start;
					msg = message.substring(start, end + 1);
				}
				else 
				{
					msg = message.substring(start);					
				}
				index = end + 1;
			} 
			catch (Exception e)
			{
				e.printStackTrace();
			}
			System.out.println("SMS::TDPropertyDetail::initializeData()::The Property Details are : "+ PropertyMap);
			pl.info("SMS::TDPropertyDetail::initializeData()::The Property Details are : "+ PropertyMap);
			pl.debug("SMS::TDPropertyDetail::initializeData()::The Property Details are : "+ PropertyMap);
			pl.warn("SMS::TDPropertyDetail::initializeData()::The Property Details are : "+ PropertyMap);
			pl.fatal("SMS::TDPropertyDetail::initializeData()::The Property Details are : "+ PropertyMap);
			pl.error("SMS::TDPropertyDetail::initializeData()::The Property Details are : "+ PropertyMap);
			pl.trace("SMS::TDPropertyDetail::initializeData()::The Property Details are : "+ PropertyMap);
			Hashtable<Object, Object> PropertyMap1 = new Hashtable<Object, Object>();
			PropertyMap1.putAll(ConvertToLower.convertHashKey(cp.getHashCommand(tdpl_tableName, msg, process)));
			if (PropertyMap1.containsKey("errorinput")) 
			{
				PropertyMap.put("ErrorInput", PropertyMap1.get("errorinput"));
				return PropertyMap;
			}
			
			/**CHECKING FOR ERRORS**/
			Hashtable<Object, Object> tempProperty1 = new Hashtable<Object, Object>();
			tempProperty1 = cp.checkError(PropertyMap1, tdpl_tableName);
			if (tempProperty1.containsKey("ErrorInput")) 
			{
				return tempProperty1;
			}
			TdPropertyList.add(PropertyMap1);
		}
		
		return PropertyMap;
	}


	
	/**
	 * initializeToUpdate() creates two vectors(old & new) of hashtables of different properties to be updated
	 */
	public StringBuffer initializeToUpdate()
	{
		ResultSet rs = null;
		String propertyChar = null;
		Command cp = new Command(request);
		int count=0;
		String msg = " ";
		
		try 
		{
			rs = DBManager.getSelect("select fieldname,spchar,order1 from command where msgtype='"+ tdpl_tableName+ "' and from_master='yes' and process='add' and order1>0 order by order1");
			rs.next();
			propertyChar = rs.getString("spchar");
			rs.close();
		}
		catch (Exception e) 
		{
			System.out.println("Property Char is not Found in Database");
			pl.info("Property Char is not Found in Database");
			pl.debug("Property Char is not Found in Database");
			pl.warn("Property Char is not Found in Database");
			pl.fatal("Property Char is not Found in Database");
			pl.error("Property Char is not Found in Database");
			pl.trace("Property Char is not Found in Database");
		}
		int index = 0;
		count = cp.getCountof(message, tdpl_tableName, process);// getCount();
		if (count != 0) 
		{
			try 
			{
				rs = DBManager.getSelect("select fieldname,spchar,order1 from command where msgtype='"+ tdpl_tableName+ "' and from_master='yes' and process='mod' and order1>0 order by order1");
				rs.next();
				TdPropertySPchar = rs.getString("spchar");
				rs.close();
				index = Index.indexOf(message, TdPropertySPchar, index + 1);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		
		String TDmsg="";
		TDmsg = message.substring(0,index);

		Hashtable<Object,Object> TdMap = new Hashtable<Object,Object>();
		TdMap.putAll(cp.getHashCommand(td_tableName,TDmsg, "add"));
		if(TdMap.containsKey("ErrorInput"))
		{
			pl.info(TdMap.toString());
			pl.debug(TdMap.toString());
			pl.warn(TdMap.toString());
			pl.fatal(TdMap.toString());
			pl.error(TdMap.toString());
			pl.trace(TdMap.toString());
			return new StringBuffer(TdMap.toString());
		}
		GetIdName gin = new GetIdName();
		TdMap = gin.convertMasterId(TdMap,td_tableName, "add");
		TdMap = GetIdName.removeno$(TdMap);
		String id = "";
		//GET TDID BY USING GIVEN CONDITION FOR TRANSACTION DETAILS
		try 
		{
			ResultSet rs1 = DBManager.getselect(TdMap,td_tableName);		
			rs1.next();
			id = rs1.getString("id");
			tdid = id;
		} catch (Exception e) 
		{
			pl.info("Please Check the Transaction ID and Item");
			pl.debug("Please Check the Transaction ID and Item");
			pl.warn("Please Check the Transaction ID and Item");
			pl.fatal("Please Check the Transaction ID and Item");
			pl.error("Please Check the Transaction ID and Item");
			pl.trace("Please Check the Transaction ID and Item");
			return new StringBuffer("Please Check the Transaction ID and Item");
			
		}
		TdMap = null;
		
		while (count != 0) 
		{
			Hashtable<Object, Object> newTransactionMap = new Hashtable<Object, Object>();
			/** It will get stores new message for Update. */
			Hashtable<Object, Object> oldTransactionMap = new Hashtable<Object, Object>();
			/** It will get stores old message for Update. */
			
			if (index == -1) 
			{
				break;
			}
			count--;
			try
			{
				int start = 0;
				int end = 0;
				start = index;
				msg = message.substring(start + 1);
				if (msg.contains(TdPropertySPchar))
				{
					end = Index.indexOf(msg, TdPropertySPchar) + start;
					msg = message.substring(start, end + 1);
				}
				else 
				{
					msg = message.substring(start);
					msg = msg.substring(0,message.length()); 					
				}
				index = end + 1;
			}
			catch (Exception e) 
			{
				e.printStackTrace();
			}
			boolean TYPEFLAG = false;
			String msg1 = "";
			String msg2 = "";
			int start = 0;
			if (msg.contains(propertyChar)) 
			{
				int end1 = 0;
				end1 = Index.indexOf(msg, propertyChar, end1 + 1);
				if (end1 == -1)
				{
					newTransactionMap.put("ErrorInput", "Item should insert");
				}
				msg1 = msg.substring(start, end1);
				TYPEFLAG = true;
			}
			else
			{
				msg1 = msg;
			}
			////////
			newTransactionMap.putAll(cp.getHashCommand(tdpl_tableName,msg1, process));
			if (newTransactionMap.containsKey("ErrorInput")) 
			{
				pl.info(newTransactionMap.toString());
				pl.debug(newTransactionMap.toString());
				pl.warn(newTransactionMap.toString());
				pl.fatal(newTransactionMap.toString());
				pl.error(newTransactionMap.toString());
				pl.trace(newTransactionMap.toString());
				return new StringBuffer(newTransactionMap.toString());
			}
			
			newTransactionMap = ConvertToLower.convertHashKey(newTransactionMap);
	
			Hashtable<Object, Object> PropertyMap = new Hashtable<Object, Object>();			
			
			PropertyMap = cp.checkError(newTransactionMap, tdpl_tableName); 
			if (PropertyMap.containsKey("ErrorInput")) 
			{
				pl.info(PropertyMap.toString());
				pl.debug(PropertyMap.toString());
				pl.warn(PropertyMap.toString());
				pl.fatal(PropertyMap.toString());
				pl.error(PropertyMap.toString());
				pl.trace(PropertyMap.toString());
				return new StringBuffer(PropertyMap.toString());
			}
			newTransactionMap.put("tdid", tdid);			
			Hashtable<Object, Object> temp1 = new Hashtable<Object, Object>();
		  	
			temp1.putAll(newTransactionMap);			
			NewTdPropertyList.add(temp1);
			if(TYPEFLAG) 
			{
				start = Index.indexOf(msg, propertyChar, start + 1);
				msg2 = msg.substring(start, msg.length());
				oldTransactionMap.putAll(cp.getHashCommand(tdpl_tableName,msg2, "add"));
				if (oldTransactionMap.containsKey("ErrorInput")) 
				{
					pl.info(oldTransactionMap.toString());
					pl.debug(oldTransactionMap.toString());
					pl.warn(oldTransactionMap.toString());
					pl.fatal(oldTransactionMap.toString());
					pl.error(oldTransactionMap.toString());
					pl.trace(oldTransactionMap.toString());
					return new StringBuffer(oldTransactionMap.toString());
				}
				
				oldTransactionMap = ConvertToLower.convertHashKey(oldTransactionMap);
								
				PropertyMap.putAll(cp.checkError(oldTransactionMap,tdpl_tableName));
				if (PropertyMap.containsKey("ErrorInput")) 
				{
					pl.info(PropertyMap.toString());
					pl.debug(PropertyMap.toString());
					pl.warn(PropertyMap.toString());
					pl.fatal(PropertyMap.toString());
					pl.error(PropertyMap.toString());
					pl.trace(PropertyMap.toString());
					return new StringBuffer(PropertyMap.toString());
				}
				//SET TDID				
				oldTransactionMap.put("tdid", tdid);				
				Hashtable<Object, Object> temp = new Hashtable<Object, Object>();
				
				temp.putAll(oldTransactionMap);
				OldTdPropertyList.add(temp);
			} 
					
		}
		pl.info(sbrDTB);
		pl.debug(sbrDTB);
		pl.warn(sbrDTB);
		pl.fatal(sbrDTB);
		pl.error(sbrDTB);
		pl.trace(sbrDTB);
		return sbrDTB;
	}
	
	
	/**
	 * initializeToView() creates hashtables of transaction_details object to be viewed 
	 * @return stringbuffer containing details of transaction_details to be viewed  
	 */
	public StringBuffer initializeToView() 
	{

			
		StringBuffer sbrProperty=new StringBuffer();
		
		Command cp = new Command(request);
		
		String msgtdpl=message;
		ResultSet rs;
		String msgtd=message;
		
		Hashtable<Object, Object> Hashtdpl=new Hashtable<Object, Object>();
		if(tdid.equals(""))
		{

		  String id = "";
		  String propertyChar="";
			try 
			{
				Hashtable<Object, Object> TransdetailsMap=new Hashtable<Object, Object>();
				try 
				{
					rs = DBManager.getSelect("select fieldname,spchar,order1 from command where msgtype='"+ tdpl_tableName+ "' and from_master='yes' and process='add' and order1>0 order by order1");
					rs.next();
					propertyChar = rs.getString("spchar");
					rs.close();
				}
				catch (Exception e) 
				{
					System.out.println("Property Char is not Found in Database");
					pl.info("Property Char is not Found in Database");
					pl.debug("Property Char is not Found in Database");
					pl.warn("Property Char is not Found in Database");
					pl.fatal("Property Char is not Found in Database");
					pl.error("Property Char is not Found in Database");
					pl.trace("Property Char is not Found in Database");
				}
				if(message.contains(propertyChar))
				{
					msgtd=message.substring(0,Index.indexOf(message, propertyChar));	
					msgtdpl=message.substring(Index.indexOf(message, propertyChar),message.length());
					Hashtdpl.putAll(cp.getHashCommand(tdpl_tableName, msgtdpl, process));
					if(Hashtdpl.containsKey("ErrorInput"))
					{
						pl.info(Hashtdpl.toString());
						pl.debug(Hashtdpl.toString());
						pl.warn(Hashtdpl.toString());
						pl.fatal(Hashtdpl.toString());
						pl.error(Hashtdpl.toString());
						pl.trace(Hashtdpl.toString());
						return new StringBuffer(Hashtdpl.toString());
					}					
				}
				TransdetailsMap.putAll(cp.getHashCommand(td_tableName, msgtd, process));
				if(TransdetailsMap.containsKey("ErrorInput"))
				{
					pl.info(TransdetailsMap.toString());
					pl.debug(TransdetailsMap.toString());
					pl.warn(TransdetailsMap.toString());
					pl.fatal(TransdetailsMap.toString());
					pl.error(TransdetailsMap.toString());
					pl.trace(TransdetailsMap.toString());
					return new StringBuffer(TransdetailsMap.toString());
				}				
				GetIdName gin = new GetIdName();
				TransdetailsMap = gin.getHashMapOfValues(TransdetailsMap);
				
				String tid=TransdetailsMap.get("tid").toString();					
				
				TransdetailsMap=gin.convertMasterId(TransdetailsMap, td_tableName, process);
				
				TransdetailsMap.put("tid",tid);
				ResultSet rs1 = DBManager.getselect(TransdetailsMap,td_tableName);				
				rs1.next();
				id = rs1.getString("id");
				tdid = id;
				
				Hashtdpl.put("tdid", tdid);
				
			} 
			catch (Exception e) {}
			
		}
		
		
		ViewHashtable.putAll(Hashtdpl);
		pl.info(sbrProperty);
		pl.debug(sbrProperty);
		pl.warn(sbrProperty);
		pl.fatal(sbrProperty);
		pl.error(sbrProperty);
		pl.trace(sbrProperty);
		return sbrProperty;
			
	}
	
	
	
	public String getId() {
		return tdid;
	}
	
	public Hashtable<Object,Object> getHashtable()	{
		return TransdetailsHash;
	}
	
	public Vector<Object> getPropertyVector() {		
		return TdPropertyList;
	}
	
	public Hashtable<Object,Object> getViewHashtable() {
		return ViewHashtable;
	}	
	
	public Vector<Object> getOldPropertyVector() {		
		return OldTdPropertyList;
	}
	
	public Vector<Object> getNewPropertyVector() {		
		return NewTdPropertyList;
	}

	
	public Hashtable<Object, Object> initializeToDelete() {
		// TODO Auto-generated method stub
		return null;
	}
	
	/**
	 * is called when process is to insert in database
	 */
	//@SuppressWarnings("unchecked")
	/*public void setProcessToAdd()
	{	
		ExecutionTimer t = new ExecutionTimer();
		 t.start();
		//add		
		TransdetailsHash.putAll(initializeToAdd());
		
		System.out.println(TransdetailsHash);
		System.out.println(TdPropertyList);		

		if(!TransdetailsHash.containsKey("ErrorInput"))
		{
			tdplBean = new Td_property_details_Bean();
			
			tdplBean.setDBManager(sqlDB);
			tdplBean.setReqParam(reqParam);
			tdplBean.setProcess(process);
			for(Object object : TdPropertyList)
			{
				Hashtable<Object ,Object> temp = (Hashtable<Object, Object>)object;
				tdplBean.setPropertyVector(temp);	
			}
			tdplBean.setTdid(tdid);
			tdplBean.insert();
		}	
		t.end();
		@SuppressWarnings("unused")
		TimerRecordFile timerFile=new TimerRecordFile("SMS.tablename","Td_property_details","processAdd",t.duration());
			
	}*/
	
	/**
	 * is called when process is to update in database
	 */
	/*public void setProcessToUpdate()
	{
		ExecutionTimer t = new ExecutionTimer();
		 t.start();
		//mod		
		sbrDTB = new StringBuffer();
		sbrDTB.append(initializeToUpdate());
		
		System.out.println("old "+OldTdPropertyList);
		System.out.println("new "+NewTdPropertyList);		
			
		tdplBean = new Td_property_details_Bean();
		
		tdplBean.setDBManager(sqlDB);
		tdplBean.setReqParam(reqParam);
		tdplBean.setProcess(process);
		
		if(!OldTdPropertyList.isEmpty())
			tdplBean.setOldPropertyVector(OldTdPropertyList);	
		if(!NewTdPropertyList.isEmpty())
			tdplBean.setNewPropertyVector(NewTdPropertyList);
		
		tdplBean.update();
		
		t.end();
		@SuppressWarnings("unused")
		TimerRecordFile timerFile=new TimerRecordFile("SMS.tablename","Td_property_details","processMod",t.duration());
			
	}*/
	
	
	/*@SuppressWarnings("unchecked")
	public void processSms()
	{		
		//add	
		if(process.equalsIgnoreCase("add"))
			processAdd();
		else
			processMod();//mod		
	}
	
	public void setProcessToView()
	{						
		//view		
	
		ExecutionTimer t = new ExecutionTimer();
		 t.start();
				
		sbrDTB = new StringBuffer();
		sbrDTB.append(initializeToView());
		
		System.out.println(ViewHashtable);
		
		tdplBean = new Td_property_details_Bean();
		
		tdplBean.setDBManager(sqlDB);
		tdplBean.setReqParam(reqParam);
		tdplBean.setProcess(process);
		
		tdplBean.setViewHashtable(ViewHashtable);
		
		sbrDTB.append(tdplBean.view());
		
		System.out.println(sbrDTB);
		
		t.end();
		@SuppressWarnings("unused")
		TimerRecordFile timerFile=new TimerRecordFile("pool.tablename","Td_property_details","getView",t.duration());
			
	}
	*/
	
}
